package com.wn.sddfp.gateway.config;

import cn.hutool.core.text.AntPathMatcher;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wn.sddfp.common.result.Result;
import com.wn.sddfp.common.result.enums.IErrorCode;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * 网关全局过滤器，实现统一鉴权：拦截所有的请求
 */
@Configuration
public class AuthFilter implements GlobalFilter {


    @Autowired
     private RedisTemplate redisTemplate;

    @Autowired
    private IgnorePathConfig ignorePathConfig;


    public static final String AUTHORIZATION = "Authorization";
    public static final String BEARER = "Bearer ";

    @SneakyThrows
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1、获取请求路径：放行一些资源
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        String path = request.getURI().getPath();
        AntPathMatcher pathMatcher = new AntPathMatcher();
        List<String> whiteList = ignorePathConfig.getWhiteList();


        boolean flag = whiteList.stream().anyMatch(urlPatter -> pathMatcher.match(urlPatter,path));
        if (flag) {
            // 放行，不进行token校验
            return chain.filter(exchange);
        }


        //7、微服务直接从请求头获取用户id
        return chain.filter(exchange);
    }

    private static Mono<Void> responseError(ServerHttpResponse response, IErrorCode resultCode) throws JsonProcessingException {
        // 返回错误
        Result<Object> result = Result.fail(resultCode);
        byte[] bytes = new ObjectMapper().writeValueAsBytes(result);
        DataBuffer dataBuffer = response.bufferFactory().wrap(bytes);
        return response.writeWith(Mono.just(dataBuffer));
    }

    public static void main(String[] args) {
        AntPathMatcher pathMatcher = new AntPathMatcher();
        // 参数1：匹配模式; /* 只匹配一层目录； /** 匹配多层目录
        // 参数2：要匹配的路径，这个路径去匹配参数1的格式
        boolean match = pathMatcher.match("/**/user", "/aa/bb/cc/user");
        System.out.println("match = " + match);
    }
}